package com.jy.modules.cims.component.image;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.exception.CimsExceptionConstant;
import com.jy.modules.cims.common.sysUtils.DateTimeUtils;
import com.jy.modules.cims.common.sysUtils.ExceptionUtils;
import com.jy.modules.cims.common.sysUtils.FTPClientImpl;
import com.jy.modules.cims.common.sysUtils.FileUtils;
import com.jy.modules.cims.common.sysUtils.IFTPClient;
import com.jy.modules.cims.common.sysUtils.PropertyUtil;
import com.jy.modules.cims.common.sysUtils.SFTPClientImpl;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.common.sysUtils.ZipFileUtils;
import com.jy.modules.cims.component.imagesign.TransReturnUrlDataDto;
import com.jy.modules.cims.data.dto.ImgurlDto;
import com.jy.modules.cims.data.interact.api.response.ResponseAttachSearchDTO;
import com.jy.modules.cims.data.interact.api.response.ResponseAttachSearchFileDTO;
import com.jy.modules.cims.sysUtils.ImgurFtpConfigInfo;
import com.jy.modules.platform.sysconfig.service.SysConfigService;
import com.jy.platform.core.fastdfs.task.SynSingleFileUploadWorker;

/**
 * @description TransferImagesHelper
 * @author shengzhoutao
 * @date 2015-09-29
 */
@Service("com.jy.modules.cims.component.image.TransferImagesHelper")
public class TransferImagesHelper {
	private static Logger logger = LoggerFactory.getLogger(TransferImagesHelper.class);

	private static final String ORG_TMP_FILE_PATH = "org.tmp.file.path";// 临时存放上传到FTP影像文件路径
	private static final String FTP_HOST_NAME = "{0}.ftp.host.name";// FTP服务器IP地址
	private static final String FTP_PORT = "{0}.ftp.port";// FTP端口号
	private static final String FTP_USER = "{0}.ftp.user";// FTP用户
	private static final String FTP_PASSWORD = "{0}.ftp.password";// FTP密码
	private static final String FTP_DIR = "{0}.ftp.dir";// FTP文件目录
	private static final String FTP_PROTOCOL = "{0}.ftp.protocol";// FTP协议
	private static final String FTP_COMPRESSED = "{0}.ftp.compressed";// 是否压缩文件上传（Y：压缩；N：不压缩）
	public static final String FTP_PROTOCOL_SFTP = "sftp";// sftp协议
	public static final String FTP_COMPRESSED_YES = "Y";// 是否压缩文件上传（Y：压缩；N：不压缩）

	@Autowired
	@Qualifier("com.jy.modules.platform.sysconfig.service.SysConfigService")
	private SysConfigService sysConfigService;
	
	/**
	 * 根据业务类型，贷款类型，转换临时目录
	 */
	public static Map<String, String> sticBizTypeMap = new HashMap<String, String>();// 业务类型转换map
	static {
		sticBizTypeMap.put(CimsConstant.DEAL_TYPE_LOAN_OUT, "loanout"); // 贷款转出
		sticBizTypeMap.put(CimsConstant.DEAL_TYPE_CREDIT_OUT, "creditout");// 债权转出
	}

	/**
	 * 
	 * @Description 根据机构编号
	 * @param cooperorgCode
	 * @return ImgurFtpConfigInfo
	 * @throws
	 * @author zhangmi
	 * @date 2015-11-18
	 */
	//@Ehcache
	public ImgurFtpConfigInfo getImgurFtpConfigInfoByCooperorgCode(final String cooperorgCode) {
		/*ImgurFtpConfigInfo imgurFtpConfigInfo = new ImgurFtpConfigInfo();
		imgurFtpConfigInfo.setFtpHostName(PropertyUtil.get(MessageFormat.format(FTP_HOST_NAME, cooperorgCode)));
		imgurFtpConfigInfo.setFtpPort(Integer.parseInt(PropertyUtil.get(MessageFormat.format(FTP_PORT, cooperorgCode))));
		imgurFtpConfigInfo.setFtpUser(PropertyUtil.get(MessageFormat.format(FTP_USER, cooperorgCode)));
		imgurFtpConfigInfo.setFtpPassword(PropertyUtil.get(MessageFormat.format(FTP_PASSWORD, cooperorgCode)));

		String ftpDir = PropertyUtil.get(MessageFormat.format(FTP_DIR, cooperorgCode));
		if (!ftpDir.endsWith("/")) {
			ftpDir = ftpDir + "/";
		}
		imgurFtpConfigInfo.setFtpDir(ftpDir);

		imgurFtpConfigInfo.setFtpCompressed(PropertyUtil.get(MessageFormat.format(FTP_COMPRESSED, cooperorgCode)));

		String tmpFilePath = PropertyUtil.get(ORG_TMP_FILE_PATH);
		if (!tmpFilePath.endsWith("/")) {
			tmpFilePath = tmpFilePath + "/";
		}
		tmpFilePath = tmpFilePath + cooperorgCode + "/";
		imgurFtpConfigInfo.setTmpFilePath(tmpFilePath);

		String ftpProtocol = "";
		try {
			ftpProtocol = PropertyUtil.get(MessageFormat.format(FTP_PROTOCOL, cooperorgCode));
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		imgurFtpConfigInfo.setFtpProtocol(ftpProtocol);

		return imgurFtpConfigInfo;*/
		
		String ftpHostName = sysConfigService.queryValueByCode(MessageFormat.format(FTP_HOST_NAME, cooperorgCode));
		String ftpPort = sysConfigService.queryValueByCode(MessageFormat.format(FTP_PORT, cooperorgCode));
		String ftpUser = sysConfigService.queryValueByCode(MessageFormat.format(FTP_USER, cooperorgCode));
		String ftpPassword = sysConfigService.queryValueByCode(MessageFormat.format(FTP_PASSWORD, cooperorgCode));
		String ftpDir = sysConfigService.queryValueByCode(MessageFormat.format(FTP_DIR, cooperorgCode));
		String ftpCompressed = sysConfigService.queryValueByCode(MessageFormat.format(FTP_COMPRESSED, cooperorgCode));
		String tmpFilePath = sysConfigService.queryValueByCode(ORG_TMP_FILE_PATH);
		String ftpProtocol = sysConfigService.queryValueByCode(MessageFormat.format(FTP_PROTOCOL, cooperorgCode));

		if(!SimpleStringUtils.hasText(ftpHostName) 
				||!SimpleStringUtils.hasText(ftpHostName) 
				||!SimpleStringUtils.hasText(ftpPort) 
				||!SimpleStringUtils.hasText(ftpUser) 
				||!SimpleStringUtils.hasText(ftpPassword) 
				||!SimpleStringUtils.hasText(ftpDir) 
				||!SimpleStringUtils.hasText(tmpFilePath) 
				||!SimpleStringUtils.hasText(ftpProtocol) ){
			return null;
		}
		ImgurFtpConfigInfo imgurFtpConfigInfo = new ImgurFtpConfigInfo();
		imgurFtpConfigInfo.setFtpHostName(ftpHostName);
		imgurFtpConfigInfo.setFtpPort(Integer.parseInt(ftpPort));
		imgurFtpConfigInfo.setFtpUser(ftpUser);
		imgurFtpConfigInfo.setFtpPassword(ftpPassword);
		imgurFtpConfigInfo.setFtpDir(!ftpDir.endsWith("/") ? (ftpDir + "/") : ftpDir);
		imgurFtpConfigInfo.setFtpCompressed(ftpCompressed);
		imgurFtpConfigInfo.setTmpFilePath((!tmpFilePath.endsWith("/") ? (tmpFilePath + "/") : tmpFilePath) + cooperorgCode + "/");
		imgurFtpConfigInfo.setFtpProtocol(ftpProtocol);

		return imgurFtpConfigInfo;
	}

	/**
	 * 
	 * @Description 根据机构编号，业务类型（deal_type），贷款类型（product_type）
	 * @param cooperorgCode
	 * @param bizType
	 * @param loanType
	 *            ImgurFtpConfigInfo
	 * @author zhangmi
	 * @date 2015-11-18
	 */
	public ImgurFtpConfigInfo getImgurFtpConfigInfoByCpcBizLoanType(final String cooperorgCode, String bizType, String loanType,
			String contractNo) {
		ImgurFtpConfigInfo imgurFtpConfigInfo = getImgurFtpConfigInfoByCooperorgCode(cooperorgCode);
		/**
		 * 设置上传目录
		 */
		String ftpDir = imgurFtpConfigInfo.getFtpDir();
		if (!ftpDir.endsWith("/")) {
			ftpDir = ftpDir + "/";
		}
		if (SimpleStringUtils.hasText(bizType)) {
			ftpDir = ftpDir + sticBizTypeMap.get(bizType) + "/";
		}
		imgurFtpConfigInfo.setFtpDir(ftpDir);

		/**
		 * 设置临时目录
		 */
		String tmpFilePath = imgurFtpConfigInfo.getTmpFilePath();
		if (!tmpFilePath.endsWith("/")) {
			tmpFilePath = tmpFilePath + "/";
		}
		if (SimpleStringUtils.hasText(bizType) && SimpleStringUtils.hasText(contractNo)) {
			tmpFilePath = tmpFilePath + sticBizTypeMap.get(bizType) + "/" + contractNo + "/";
		}
		imgurFtpConfigInfo.setTmpFilePath(tmpFilePath);

		return imgurFtpConfigInfo;
	}

	/**
	 * @description 根据配置文件获取不同FTP客户端
	 * @param imgurFtpConfigInfo
	 *            配置文件信息
	 * @return ftpClient FTP客户端实现类
	 */
	public IFTPClient getFTPClient(final ImgurFtpConfigInfo imgurFtpConfigInfo) {
		IFTPClient ftpClient = null;
		if (FTP_PROTOCOL_SFTP.equalsIgnoreCase(imgurFtpConfigInfo.getFtpProtocol())) {
			ftpClient = new SFTPClientImpl();
		} else {
			ftpClient = new FTPClientImpl();
		}

		ftpClient.init(imgurFtpConfigInfo.getFtpHostName(), imgurFtpConfigInfo.getFtpPort(), imgurFtpConfigInfo.getFtpUser(),
				imgurFtpConfigInfo.getFtpPassword());

		return ftpClient;
	}

	/**
	 * @description 登录FTP
	 * @param ftpClient
	 *            FTP客户端实现类
	 * @return 成功：true；false：失败
	 */
	public boolean loginFTP(IFTPClient ftpClient) {
		boolean isLogin = false;

		isLogin = ftpClient.ftpLogin();
		if (!isLogin) {
			return false;
		}

		return true;
	}

	/**
	 * @description 退出FTP
	 * @param ftpClient
	 *            FTP客户端实现类
	 */
	public void logOutFTP(IFTPClient ftpClient) {
		if (null != ftpClient) {
			ftpClient.ftpLogOut();

			ftpClient = null;
		}
	}

	/**
	 * @description 上传文件到Ftp
	 * @param contractNo
	 *            合同号
	 * @param imgurFtpConfigInfo
	 *            配置文件信息
	 * @return
	 */
	public boolean uploadImagesFile(final ImgurFtpConfigInfo imgurFtpConfigInfo, final TransferImagesDto transferImagesDto) {
		IFTPClient ftpClient = null;
		try {
			// 根据配置文件获取不同FTP客户端
			ftpClient = getFTPClient(imgurFtpConfigInfo);

			// 登录FTP
			if (!loginFTP(ftpClient)) {
				return false;
			}
			String ftpDir = getFtpDir(imgurFtpConfigInfo, transferImagesDto);
			// 压缩文件上传单个文件
			if (FTP_COMPRESSED_YES.equalsIgnoreCase(imgurFtpConfigInfo.getFtpCompressed())) {
				String zipFileUrl = getZipFileURL(imgurFtpConfigInfo, transferImagesDto);// 文件绝对路径
				return ftpClient.uploadFile(new File(zipFileUrl), ftpDir);
			}
			// 非压缩文件将整个下载好的所有文件夹都上传
			else {
				String downDir = getDownDir(imgurFtpConfigInfo, transferImagesDto);
				return ftpClient.uploadDirectory(downDir, ftpDir);
			}
		} catch (Exception e) {
			logger.error(CimsExceptionConstant.TRANSFER_IMG_FAIL, e);
		} finally {
			// 退出FTP
			logOutFTP(ftpClient);
		}
		return false;
	}
	
	/**
	 * @description 从url下载多个文件到本地
	 * @param imgurFtpConfigInfo
	 * @param imgurlDtoList
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	public boolean downloadURLImg(final ImgurFtpConfigInfo imgurFtpConfigInfo, final List<ImgurlDto> imgurlDtoList) throws IOException {
		for (ImgurlDto imgurl : imgurlDtoList) {
			String attachUrl = imgurl.getAttachUrl();// 文件URL
			String contractNo = imgurl.getContractNo();// 合同编号
			String localDires = SimpleStringUtils.append(imgurFtpConfigInfo.getTmpFilePath(), contractNo, "/");// TransferImagesHelper.getDownDir(imgurFtpConfigInfo,
																											// imgurl);
			// 如果是房贷，车贷。多一层押品编号目录
			if (SimpleStringUtils.hasText(imgurl.getGuarNo())) {
				localDires = SimpleStringUtils.append(localDires, imgurl.getGuarNo(), "/");
			}
			// 本地目录
			if (!SimpleStringUtils.hasText(attachUrl) || !SimpleStringUtils.hasText(contractNo) || !SimpleStringUtils.hasText(localDires)) {
				return false;
			}

			String[] attachUrlArray = attachUrl.split("/");
			String remoteFileName = attachUrlArray[attachUrlArray.length - 1];// 待下载文件名称

			boolean downloadSuccess = false;
			try {
				FileUtils.downLoadFromUrl(attachUrl, remoteFileName, localDires);
				downloadSuccess = true;
			} catch (MalformedURLException e) {
				downloadSuccess = false;
			} catch (Exception e) {
				downloadSuccess = false;
			}
			if (!downloadSuccess) {
				return false;
			}
		}
		return true;
	}

	/**
	 * @description 多线程从url下载多个文件到本地
	 * @param imgurFtpConfigInfo
	 * @param transferImagesDto
	 * @param imgurlDtoList
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	public boolean downloadURLImgForMoreThread(final ImgurFtpConfigInfo imgurFtpConfigInfo, final TransferImagesDto transferImagesDto,
			final List<ImgurlDto> imgurlDtoList) throws IOException {
		String localDires = getTempDir(imgurFtpConfigInfo, transferImagesDto);// 本地目录
		for (ImgurlDto imgurl : imgurlDtoList) {
			String attachUrl = imgurl.getAttachUrl();// 文件URL
			String[] attachUrlArray = attachUrl.split("/");
			String remoteFileName = attachUrlArray[attachUrlArray.length - 1];// 待下载文件名称
			
			if (!SimpleStringUtils.hasText(attachUrl) || !SimpleStringUtils.hasText(localDires)) {
				return false;
			}

			boolean downloadSuccess = false;
			try {
				
				downloadSuccess = FileDownloader.getFileDownloader().download(new URL(attachUrl), Paths.get(localDires + remoteFileName));
			} catch (MalformedURLException e) {
				downloadSuccess = false;
			} catch (Exception e) {
				downloadSuccess = false;
			}
			
			if (!downloadSuccess) {
				return false;
			}
		}
		return true;
	}

	/**
	 * @description 创建临时文件目录
	 * @param localTmpPath
	 *            本地(临时)存放下载影像文件
	 */
	public void createTempDir(final String localTmpPath) {
		// 删除临时目录
		FileUtils.deleteDirectory(localTmpPath);
		// 创建临时目录
		FileUtils.createDir(localTmpPath);
	}

	/**
	 * 根据机构，业务编号获取临时目录，进行删除
	 * 
	 * @Description
	 * @param cooperorgCode
	 * @param bizType
	 * @throws Exception
	 * @date 2015-11-14
	 */
	public void deleteDirByCpcBizType(String cooperorgCode, String bizType) throws Exception {
		String tmpFilePath = PropertyUtil.get(ORG_TMP_FILE_PATH);
		tmpFilePath = tmpFilePath + cooperorgCode + "/";
		if (SimpleStringUtils.hasText(bizType)) {
			tmpFilePath = tmpFilePath + sticBizTypeMap.get(bizType) + "/";
		}
		// 根据机构，业务编号删除临时目录
		FileUtils.deleteDirectory(tmpFilePath);
	}

	/**
	 * @description 压缩影像文件
	 * @param zipDirectory
	 *            需要压缩的文件夹名
	 * @param zipFileName
	 *            压缩后的zip文件名，如果后缀不是".zip, .jar, .war"， 自动添加后缀".zip"。
	 * @return
	 * @throws Exception
	 */
	public boolean zipFile(String zipDirectory, String zipFileName) {
		String zipResult = ZipFileUtils.zip(zipDirectory, zipFileName, false);
		if (SimpleStringUtils.hasText(zipResult)) {
			logger.error(zipResult);
			return false;
		}
		return true;
	}

	/**
	 * @description 清理数据
	 * @param imgurFtpConfigInfo
	 *            配置参数
	 * @param transferImagesDto
	 *            影像对象
	 */
	public void delDealData(final ImgurFtpConfigInfo imgurFtpConfigInfo, final TransferImagesDto transferImagesDto) {
		if (null != imgurFtpConfigInfo && null != transferImagesDto) {
			if (SimpleStringUtils.hasText(imgurFtpConfigInfo.getTmpFilePath())) {
				FileUtils.deleteDirectory(getTempDir(imgurFtpConfigInfo, transferImagesDto));
			}
		}
	}

	/**
	 * @description 清理队列数据
	 */
	public void clearAllTransferImagesQueue() {
		TransferImagesQueue.downQueue.clear();
		TransferImagesQueue.zipQueue.clear();
		TransferImagesQueue.uploadQueue.clear();
	}

	/**
	 * @description 创建临时文件目录
	 * @param imgurFtpConfigInfo
	 * @param transferImagesDto
	 * @return
	 */
	public void createTempDir(ImgurFtpConfigInfo imgurFtpConfigInfo, TransferImagesDto transferImagesDto) {
		String localTmpPath = getTempDir(imgurFtpConfigInfo, transferImagesDto);
		createTempDir(localTmpPath);
	}

	/**
	 * @description 获取临时目录
	 * @param imgurFtpConfigInfo
	 * @param transferImagesDto
	 * @return
	 */
	public String getTempDir(ImgurFtpConfigInfo imgurFtpConfigInfo, TransferImagesDto transferImagesDto) {
		String localTmpPath = imgurFtpConfigInfo.getTmpFilePath();
		localTmpPath = SimpleStringUtils.append(localTmpPath, transferImagesDto.getDealType(), "/", transferImagesDto.getContractNo(), "/");

		return localTmpPath;
	}

	/**
	 * @description 获取FTP上传目录
	 * @param imgurFtpConfigInfo
	 * @param transferImagesDto
	 * @return
	 */
	public String getFtpDir(ImgurFtpConfigInfo imgurFtpConfigInfo, TransferImagesDto transferImagesDto) {
		String dealType = transferImagesDto.getDealType() == null ? "" : transferImagesDto.getDealType();
		dealType = sticBizTypeMap.get(dealType);
		dealType = (dealType == null ? transferImagesDto.getDealType() : dealType);

		String ftpDir = imgurFtpConfigInfo.getFtpDir();
		String dealDate = DateTimeUtils.formatDate(transferImagesDto.getDealDate(), DateTimeUtils.DEFAULT_DATE_FORMAT);
		ftpDir = SimpleStringUtils.append(ftpDir, dealType, "/", dealDate, "/", transferImagesDto.getCreditPackageName(), "/");

		return ftpDir;
	}

	/**
	 * @description 获取下载目录
	 * @param imgurFtpConfigInfo
	 * @param transferImagesDto
	 * @return
	 */
	public String getDownDir(final ImgurFtpConfigInfo imgurFtpConfigInfo, final TransferImagesDto transferImagesDto) {
		return getTempDir(imgurFtpConfigInfo, transferImagesDto);
	}

	/**
	 * @description 获取ZIP目录 D:\\downfile\\
	 * @param imgurFtpConfigInfo
	 * @param transferImagesDto
	 * @return
	 */
	public String getZipDir(final ImgurFtpConfigInfo imgurFtpConfigInfo, final TransferImagesDto transferImagesDto) {
		return getTempDir(imgurFtpConfigInfo, transferImagesDto);
	}

	/**
	 * @description 获取ZIP文件名称 123456.zip
	 * @param imgurFtpConfigInfo
	 * @param transferImagesDto
	 * @return
	 */
	public String getZipFileName(final TransferImagesDto transferImagesDto) {
		String contractNo = transferImagesDto.getContractNo();
		return SimpleStringUtils.append(contractNo, ".zip");
	}

	/**
	 * @Description 获取ZIP文件夹路径 :D:\\downfile\\123456.zip
	 * @param imgurFtpConfigInfo
	 * @param transferImagesDto
	 * @author zhangmi
	 * @date 2015-11-18
	 */
	public String getZipFileURL(final ImgurFtpConfigInfo imgurFtpConfigInfo, final TransferImagesDto transferImagesDto) {
		String zipFileUrl = getTempDir(imgurFtpConfigInfo, transferImagesDto) + getZipFileName(transferImagesDto);
		return zipFileUrl;
	}
	

	/**
	 * 下载文件信息（向上压缩包zip）
	 * @author zhangmi
	 * @date  2016年12月21日
	 * @param imgurFtpConfigInfo
	 * @return 下载的目录
	 */
	public String downloadZipFile(final ImgurFtpConfigInfo imgurFtpConfigInfo,ResponseAttachSearchDTO responseAttachSearchDto) throws Exception{
		

		String downLocalPath = null;
		String filePath = responseAttachSearchDto.getFilePath();
		
		// 本地目录
		if (!SimpleStringUtils.hasText(filePath)) {
			return null;
		}
		//下载的文件名称（12893.zip）
		String[] attachUrlArray = filePath.split("/");
		String remoteFileName = attachUrlArray[attachUrlArray.length - 1];// 待下载文件名称

		//下载的临时目录
		String localDir = getCreateLocalDir(imgurFtpConfigInfo.getTmpFilePath(),remoteFileName);
		if (!SimpleStringUtils.hasText(localDir)) {
			return null;
		}
		try {
			FileUtils.downLoadFromUrl(filePath, remoteFileName, localDir);
			downLocalPath = localDir;
			return downLocalPath;
		} catch (MalformedURLException e) {
			e.printStackTrace();
			throw new Exception("MalformedURLException 异常检查URL！"+ExceptionUtils.getStackTraceAsString(e));
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("下载压缩包异常！"+ExceptionUtils.getStackTraceAsString(e));
		}
	}
	
	/**
	 * 目录i
	 * @author zhangmi
	 * @date  2016年12月30日
	 * @param imgurFtpConfigInfo
	 * @param responseAttachSearchDto
	 * @return
	 */
	public String downLoadFTPImg(final ImgurFtpConfigInfo imgurFtpConfigInfo, final ResponseAttachSearchDTO responseAttachSearchDto)throws Exception{
		IFTPClient ftpClient = null;
		try {
			// 根据配置文件获取不同FTP客户端
			ftpClient = getFTPClient(imgurFtpConfigInfo);
			String filePath = responseAttachSearchDto.getFilePath();
			
			//
			if (!SimpleStringUtils.hasText(filePath)) {
				logger.info("FTP文件下载地址为空！");
				return null;
			}
			
			//下载的文件名称（12893.zip）
			String[] attachUrlArray = filePath.split("/");
			String remoteFileName = attachUrlArray[attachUrlArray.length - 1];// 待下载文件名称

			//下载的临时目录
			String localDir = getCreateLocalDir(imgurFtpConfigInfo.getTmpFilePath(),remoteFileName);
			if (!SimpleStringUtils.hasText(localDir)) {
				logger.info("FTP文件下载本地目录为空！");
				return null;
			}
			createTempDir(localDir);
			

			// 登录FTP-下载文件
			if (!loginFTP(ftpClient)) {
				return null;
			}
			ftpClient.downloadFile(filePath, getFullLoadUrl(localDir,remoteFileName));
			return localDir;
		} catch (Exception e) {
			logger.error("影像文件下载失败！{}", e);
			throw new Exception("影像文件下载失败！");
		} finally {
			// 退出FTP
			logOutFTP(ftpClient);
		}
	}
	
	/**
	 * 获取全路径
	 * @author zhangmi
	 * @date  2016年12月30日
	 * @param localDir
	 * @param fileName
	 * @return
	 */
	public String getFullLoadUrl(String localDir,String fileName){
		if(localDir.endsWith("/")){
			return SimpleStringUtils.append(localDir,fileName);
		}else{
			return SimpleStringUtils.append(localDir,"/",fileName);
		}
	}
	
	/**
	 * 获取下载目录
	 * @author zhangmi
	 * @date  2016年12月21日
	 * @param dir
	 * @return
	 */
	public String getCreateLocalDir(String dir,String remoteFileName){
		//获取文件名字（不含.zip）
		String fileDirName = remoteFileName.substring(0,remoteFileName.indexOf("."));
		return SimpleStringUtils.append(dir,"/",fileDirName,"/");
	}
	
	/**
	 * 解压缩（仅支持ZIP）
	 * @author zhangmi
	 * @date  2016年12月21日
	 * @param zipDirectory
	 * @param zipDestPath
	 * @return
	 */
	public boolean unZipFile(String zipDirectory, String zipDestPath) throws Exception{
		String zipResult = ZipFileUtils.unZip(new File(zipDirectory), zipDestPath);
		if (SimpleStringUtils.hasText(zipResult)) {
			logger.error(zipResult);
			return false;
		}
		return true;
	}
	
	
	/**
	 * 获取指定文件下所有的file文件,返回文件集合
	 * @author zhangmi
	 * @date  2016年12月22日
	 * @param file
	 * @param resultFile
	 * @return
	 */
	public List<String> getFilesByDirectory(File file,List<String> resultFilePath){
        File[] files = file.listFiles();
        if(files==null)return resultFilePath;// 判断目录下是不是空的
        for (File f : files) {
            if(f.isDirectory()){// 判断是否文件夹
            	getFilesByDirectory(f,resultFilePath);// 调用自身,查找子目录
            }else
            	resultFilePath.add(f.getPath());
        }
        return resultFilePath;
    }
	/**
	 * 
	 * @author zhangmi
	 * @date  2016年12月22日
	 * @param listFilePaths
	 * @param list
	 * @param returnFiles
	 */
	public void getCompareFiles(List<String> listFilePaths,List<ResponseAttachSearchFileDTO> list,List<TransReturnUrlDataDto> returnFiles)  throws Exception{
		TransReturnUrlDataDto tmpFile = null;
		try {
			for (String  path: listFilePaths) {
				for (ResponseAttachSearchFileDTO responseAttachSearchFileDTO : list) {
					//String fileName = responseAttachSearchFileDTO.getFileName();
					String fileRealName = responseAttachSearchFileDTO.getFileRealName();
					if(path.contains(fileRealName)){
						tmpFile = new TransReturnUrlDataDto();
						tmpFile = TransReturnUrlDataDto.entityToCopy(tmpFile, responseAttachSearchFileDTO);
						tmpFile.setFileLocalPath(path);
						tmpFile.setAttachSize(String.valueOf(FileUtils.getFileSize(path)));
//						tmpFile.setCodeName("N1_35.pdf");
//						tmpFile.setAttachTypeItem("N1_35");
						returnFiles.add(tmpFile);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("获取文件比对信息失败！"+ExceptionUtils.getStackTraceAsString(e));
		}
	}

	
	private SynSingleFileUploadWorker synSingleFileUploadWorker;
	
	/**
	 * 创建影像列表长传对象
	 * @author zhangmi
	 * @date  2017年1月3日
	 * @throws Exception
	 */
	public void init() throws Exception{
		if(synSingleFileUploadWorker==null){
			synSingleFileUploadWorker = new SynSingleFileUploadWorker();
		}
	}
	/**
	 * 文件上传到影像服务器
	 * @author zhangmi
	 * @date  2016年12月23日
	 * @param list
	 */
	public List<TransReturnUrlDataDto> uploadFileKey(List<TransReturnUrlDataDto> list) throws Exception{
		init();
		for (TransReturnUrlDataDto fileTempDto : list) {

			String localPath = fileTempDto.getFileLocalPath();
			String fileRealName = fileTempDto.getFileRealName();
			try {
				String key = synSingleFileUploadWorker.upload(FileUtils.getBytes(localPath), null, fileRealName);
				fileTempDto.setAttachUrl(key);
			} catch (Exception e) {
				e.printStackTrace();
				throw new Exception("上传文件到影像服务器失败！"+ExceptionUtils.getStackTraceAsString(e));
			} 
		}
		return list;
	}
	
	/**
	 * @Description 获取是否多线程处理影像文件
	 * @return true：是；false：否
	 */
	public Boolean isMoreThread() {
		// // 在系统管理-》参数管理，配置启用多线程处理影像文件：MORE_THREAD_TRANSFER_IMAGES
		try {
			String controlFlag = sysConfigService.queryValueByCode("MORE_THREAD_TRANSFER_IMAGES");
			if (CimsConstant.FLAG_YES.equalsIgnoreCase(controlFlag)) {
				return true;
			}
		} catch (Exception e) {
			logger.info(e.getMessage());
		}
		return false;
	}
}
